﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Intorise.Common;
using Config;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace Model
{
    public partial class Player
    {
        static string GET_GIFT_URL = "http://hdapi.37.com/?c=dtsdqxzkf20151117&a=gift_first_charge&alias_info=dtsdqxzkf20151117&f=201511&callback=a&_={0}";
        static string GET_LOGIN_GIFT_URL = "http://hdapi.37.com/?c=dtsdqxzkf20151117&a=gift_login&alias_info=dtsdqxzkf20151117&f=201511&callback=a&day=1&_={0}";
        ManualResetEvent cleanBackpackEvent = new ManualResetEvent(true);
        ManualResetEvent mailboxOpend = new ManualResetEvent(true);
        ManualResetEvent 贵宾物品已获得 = new ManualResetEvent(true);
        ManualResetEvent 寻宝结果 = new ManualResetEvent(true);
        ManualResetEvent 寻宝券已获得 = new ManualResetEvent(true);
        bool tradeCompleted = false;

        #region Processor
        public void InitProcessor()
        {
            if (Initialized) { return; }
            Initialized = true;
            engine.RegisterProcessor(new Processor("ProcessAttackMonster", MessageTypeEnum.Attack, ProcessAttackMonster));
            engine.RegisterProcessor(new Processor("ProcessServerResult", MessageTypeEnum.ServerResult, ProcessServerResult));
            engine.RegisterProcessor(new Processor("ProcessMapEntered", MessageTypeEnum.MapEntered, ProcessMapEntered));
            engine.RegisterProcessor(new Processor("ProcessLocationChanged", MessageTypeEnum.LocationChanged, ProcessLocationChanged));
            engine.RegisterProcessor(new Processor("ProcessPlayerMoved", MessageTypeEnum.PlayerMoved, ProcessPlayerMoved));
            engine.RegisterProcessor(new Processor("ProcessHP", MessageTypeEnum.HeathPointChanged, ProcessHP));
            engine.RegisterProcessor(new Processor("ProcessUnderAttack", MessageTypeEnum.UnderAttack, ProcessUnderAttack));
            engine.RegisterProcessor(new Processor("ProcessMpChanged", MessageTypeEnum.MpChanged, ProcessMpChanged));
            engine.RegisterProcessor(new Processor("ProcessHpChanged", MessageTypeEnum.HpChanged, ProcessHpChanged));
            engine.RegisterProcessor(new Processor("ProcessGoldChanged", MessageTypeEnum.GoldChanged, ProcessGoldChanged));
            engine.RegisterProcessor(new Processor("ProcessItemBuy", MessageTypeEnum.ItemGeted, ProcessItemBuy));
            engine.RegisterProcessor(new Processor("ProcessItemBuy0", MessageTypeEnum.ItemGeted0, ProcessItemBuy));
            engine.RegisterProcessor(new Processor("ProcessItemDroped", MessageTypeEnum.ItemDroped, ProcessItemDroped));
            engine.RegisterProcessor(new Processor("ProcessItemPickuped", MessageTypeEnum.ItemPickuped, ProcessItemPickuped));
            engine.RegisterProcessor(new Processor("ProcessRide", MessageTypeEnum.Ride, ProcessRide));
            engine.RegisterProcessor(new Processor("ProcessSignCount", MessageTypeEnum.SignCount, ProcessSignCount));
            engine.RegisterProcessor(new Processor("ProcessLevelUp", MessageTypeEnum.LevelUp, ProcessLevelUp));
            engine.RegisterProcessor(new Processor("SellEquipment", MessageTypeEnum.SellEquipment, SellEquipment));
            engine.RegisterProcessor(new Processor("ProcessCleanBackpack", MessageTypeEnum.CleanBackpack, ProcessCleanBackpack));
            engine.RegisterProcessor(new Processor("ProcessAgreeTrade", MessageTypeEnum.AgreeTrade, ProcessAgreeTrade));
            engine.RegisterProcessor(new Processor("ProcessLockTrade", MessageTypeEnum.LockTrade, ProcessLockTrade));
            engine.RegisterProcessor(new Processor("ProcessGetGift", MessageTypeEnum.GiftUrl, ProcessGiftUrl));
            engine.RegisterProcessor(new Processor("ProcessMailData", MessageTypeEnum.MailData, ProcessMailData));


            engine.RegisterProcessor(new Processor("ProcessTreasureData", MessageTypeEnum.Treasure, ProcessTreasureData));
        }



        public bool ProcessUnderAttack(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var msg = new UnderAttackMsg(x.Data);
                if (msg.AttackerID == this.ID)//攻击怪物
                {
                    if (logDebugInfo) { ConsoleBLL.WriteLineInfo(string.Format("UnderAttack：{0} 攻击怪物，伤害{1}，当前血量{2}", this, msg.Damage, msg.CurrentHP)); }

                    if (msg.CurrentHP <= 0)//杀死怪物
                    {
                        var monster = engine.GetMonster(msg.TargetID);
                        if (monster != null)
                        {
                            monster.Alive = false;
                        }
                        KilledCount++;
                        if (logDebugInfo) ConsoleBLL.WriteLine(msg.TargetID.ToString("X2") + "怪物已死亡");
                    }
                }
                else if (msg.TargetID == this.ID)
                {
                    //if (logDebugInfo) { ConsoleBLL.WriteLine(string.Format("UnderAttack：{0}被怪物{1} 攻击，伤害{2}，当前血量{3}", this, msg.AttackerID.ToString("X2"), msg.Damage, msg.CurrentHP)); }
                    //TreatHP(msg.CurrentHP);
                    //if (this.Status == PlayerStatusEnum.自动打怪)
                    //{
                    //    engine.Found(new Monster { InstanceID = msg.AttackerID, Location = this.Location });
                    //}
                }
            //});
            return true;
        }

        public bool ProcessAttackMonster(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var msg = new AttackMsg(x.Data);
                if (msg.AttackerID == this.ID)//攻击怪物
                {
                    if (logDebugInfo) { ConsoleBLL.WriteLine(string.Format("AttackMonster：{0} 攻击怪物，伤害{1}，当前血量{2}", this, msg.Damage, msg.CurrentHP)); }

                    if (msg.CurrentHP <= 0)//杀死怪物
                    {
                        var monster = engine.GetMonster(msg.TargetID);
                        if (monster != null)
                        {
                            monster.Alive = false;
                        }
                        KilledCount++;
                        if (logDebugInfo) ConsoleBLL.WriteLine(msg.TargetID.ToString("X2") + "怪物已死亡");
                    }
                }
                else if (msg.TargetID == this.ID)
                {
                    var msg1 = new UnderAttackMsg(x.Data);
                    if (logDebugInfo) { ConsoleBLL.WriteLine(string.Format("AttackMonster：{0}被怪物{1} 攻击，伤害{2}，当前血量{3}", this, msg1.AttackerID.ToString("X2"), msg1.Damage, msg1.CurrentHP)); }
                    TreatHP1(msg1.CurrentHP);
                    if (this.Status == PlayerStatusEnum.自动打怪)
                    {
                        engine.Found(new Monster { InstanceID = msg1.AttackerID, Location = this.Location });
                    }
                    else if (this.Status != PlayerStatusEnum.前往挂机地点)
                    {
                        //var monster = new Monster { InstanceID = msg.KillerID };
                        //Thread thread = new Thread(new ParameterizedThreadStart(y =>
                        //{
                        //    while (monster.Alive)
                        //    {
                        //        skillList.ForEach(f => { KillMonster(f, monster); });
                        //    }
                        //}));
                        //thread.Start();
                    }
                    //ConsoleBLL.WriteLine(this + " " + msg.KillerID + "攻击" + msg.TheKilled + "，伤害：" + msg.Damage);
                }

            //});
            return true;
        }

        public bool ProcessServerResult(Message x)
        {
            GameHelper.Run(x, r =>
            {
                var msg = new ResultMsg(x.Data);


                if (msg.ResultText.Contains("恭喜您获得"))//购买返回
                {
                    //ProcessItemGot(msg);
                }
                else if (msg.ResultText.Contains("拾取的物品太远"))
                {
                    ((BotConfig)ConfigManager.BusinessConfig).GetItemDistance = 0;
                }
                if (msg.ResultText.Contains("包裹位置不足"))
                {
                    ConsoleBLL.WriteLineError(this.ToString() + " " + msg.ResultText);
                    this.Status = PlayerStatusEnum.包裹已满;
                }
                else if (msg.ResultText.Contains("死亡状态下") || msg.ResultText.Contains("您已经死亡") || msg.ResultText.Contains("您被怪物【{1}】击败了"))
                {
                    Thread.Sleep(5000);
                    Revive();
                    return;
                    //ConsoleBLL.WriteLineError(this.ToString() + " " + msg.ResultText);
                    //this.Quit();
                }
                else if (msg.ResultText.Contains("捡到"))
                {
                    #region 捡到
                    PickupItemMsg item = new PickupItemMsg(msg.Data);
                    ConsoleBLL.WriteLineWaring(this.ToString() + " " + msg.ResultText);
                    if ((NeedPickupGold == true) && (item.Name.Contains("女神") || item.Name.Contains("精灵") || item.Name.Contains("风之") || item.Name.Contains("藤之") || item.Name.Contains("弩") || item.Name.Contains("弓") || item.Name.Contains("之虎") || item.Name.Contains("红羽") || item.Name.Contains("圣灵")))
                    {

                        return;
                    }
                    lock (Items)
                    {


                        var lastItem = Items.LastOrDefault();
                        if (lastItem != null && lastItem.Name == "未知物品")
                        {
                            lastItem.Name = item.Name;
                        }
                        if (lastItem != null && IsNeedSell(lastItem.Name))
                        {
                            Sell(lastItem);
                            Items.Remove(lastItem);
                        }
                        var list = Items.GroupBy(g => g.Name).ToList();
                        SumItems(list);
                    }

                    lock (medicinals)
                    {
                        if (medicinals.Count > 3)
                        {
                            medicinals.ForEach(m =>
                            {
                                Sell(m);
                                medicinals.Remove(m);
                            });
                        }
                    }
                    #endregion
                }
                else if (msg.ResultText.Contains("魔法值不足"))
                {

                    PauseAutoFight = true;

                    for (int i = 0; i < 5; i++)
                    {
                        Treat(Thing.MedicinalType.MP0);
                        //     Thread.Sleep(5000);
                    }
                    PauseAutoFight = false;
                }
                else if (msg.ResultText.Contains("所需金币不足"))
                {
                    //int i = 0;
                    //PickupItemMsg item = new PickupItemMsg(msg.Data);

                }
                else if (msg.ResultText.Contains("经验"))
                {
                    string expString = Tools.SubString(msg.ResultText, ">", "<", true);
                    if (expString == "")
                    {
                        expString = Tools.SubString(msg.ResultText, "........", "....", true);
                    }
                    //获得{1}{2}经验........21074....
                    int exp = 0;
                    int.TryParse(expString, out exp);
                    Exp += exp;
                    ExpRange = Math.Round((double)Exp / (DateTime.Now - startAutoFightTime).TotalMinutes / 10000, 2);
                }
                else if (msg.ResultText.Contains("目标线路未找到"))
                {
                    ConsoleBLL.WriteLineWaring(this + " " + msg.ResultText);
                    Change(new Random().Next(3) + 1);
                }
                else if (logServerInfo)
                {
                    ConsoleBLL.WriteLine(this.ToString() + " " + msg.ResultText);
                }
            });
            return true;
        }

        public bool ProcessMapEntered(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var item = new MapEnteredMsg(x.Data);
                this.Location = item.Location;
                this.X = item.X;
                this.Y = item.Y;
                this.Line = item.Line;
                ConsoleBLL.WriteLineInfo(this + " 进入地图，当前坐标：" + item.Location);
            //});
            return true;
        }

        public bool ProcessLocationChanged(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var item = new LocationChangedMsg(x.Data);
                if (this.ID == item.UserID)
                {
                    this.Location = item.Location;
                    this.X = item.X;
                    this.Y = item.Y;
                    if (logDebugInfo) ConsoleBLL.WriteLineInfo(this + " 当前坐标：" + item.Location);
                }
            //});
            return true;
        }

        public bool ProcessPlayerMoved(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var item = new PlayerMovedMsg(x.Data);
                if (item.MoverID == this.ID)
                {
                    if (logDebugInfo) ConsoleBLL.WriteLineInfo("从" + item.Location + "移动到" + Tools.GetHexString(item.MoveData, item.MoveData.Length));
                }
                else
                {
                    //ConsoleBLL.WriteLineInfo(item.MoverID.ToString("X2") + "从" + item.Location + "移动" + Tools.GetHexString(item.MoveData, item.MoveData.Length));
                }
            //});
            return true;
        }

        public bool ProcessHP(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var item = new HeathPointChangedMsg(x.Data);
                if (item.OwnerID == this.ID)
                {
                    int HpMax = 0;
                    TreatHP(item.CurrentHP, HpMax);
                    if (logDebugInfo) ConsoleBLL.WriteLineInfo(this + string.Format(" 血量：{1}/{2}", item.OwnerID.ToString("X2"), item.CurrentHP, item.TotalHP));
                }
                else
                {
                    //ConsoleBLL.WriteLineInfo(string.Format("{0}血量：{1}/{2}", item.OwnerID.ToString("X2"), item.CurrentHP, item.TotalHP));
                }
            //});
            return true;
        }

        public bool ProcessMpChanged(Message x)
        {
            GameHelper.Run(x, r =>
            {
                var item = new MpChangedMsg(x.Data);
                if (item.ID == this.ID)
                {
                    this.CurrentMP = item.CurrentMP;
                    if (TotalMP < CurrentMP) { TotalMP = CurrentMP; }
                    double mpRange = (double)this.CurrentMP / TotalMP;
                    if (mpRange <= (double)Config.MP2 / 100)
                    {
                        Treat(Thing.MedicinalType.MP2);
                    }
                    else if (mpRange <= (double)Config.MP1 / 100)
                    {
                        if (medicinals.Count(w => w.Type == 6) == 0)//没有大蓝在买
                        {
                            Treat(Thing.MedicinalType.MP1);
                        }
                    }
                    else if (mpRange <= (double)Config.MP0 / 100)
                    {
                        lock (medicinals)
                        {
                            if (medicinals.Count(w => w.Type == 4) == 0 || medicinals.Count(w => w.Type == 6) == 0)//没有大蓝和中蓝在买
                            {
                                Treat(Thing.MedicinalType.MP0);
                            }
                        }
                    }
                }
                else
                {

                }
            });
            return true;
        }

        public bool ProcessHpChanged(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var item = new HpChangedMsg(x.Data);

                if (item.ID == this.ID)
                {

                    int HpMax = 1;
                    //ConsoleBLL.WriteLineInfo(string.Format("HP：{0}/{1}", item.CurrentHP, TotalHP));
                    TreatHP(item.CurrentHP, HpMax);

                }
                else
                {

                }
            //});
            return true;
        }

        public bool ProcessGoldChanged(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var item = new GoldChangedMsg(x.Data);
                this.TotalGold = item.GoldCount;
                this.GoldID = item.GoldID;
                //ConsoleBLL.WriteLineInfo(string.Format("Gold：{0}", item.GoldCount));
            //});
            return true;
        }

        //购物返回
        public bool ProcessItemBuy(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var item = new ItemGetedMsg(x.Data);
                byte Position = 11;
                if (item.Item != null)
                {
                    if (item.Item.Name == "熊猫" || item.Item.Name == "恶魔")
                    {
                        ZhuangBei(item.InstanceID, this.Version, Position);
                        return true;
                    }
                    else if (item.Item.Name.Contains("经验") || item.Item.Name.Contains("会员") || item.Item.Name.Contains("攻速"))
                    {
                        UseItem(item.Item);
                    }
                    //else if (item.Item.Name.Contains("之翼"))
                    //{
                    //    EquipItem(item.Item);
                    //}
                    else if (item.Item is Medicinal)
                    {
                        lock (medicinals)
                        {
                            if (medicinals.Count(c => c.InstanceID == item.Item.InstanceID) == 0)
                            {
                                medicinals.Add((Medicinal)item.Item);
                            }
                        }
                    }
                    lock (lastBuyMedicinals)
                    {
                        var medicinal = lastBuyMedicinals.FirstOrDefault(w => w.Name == item.Item.Name);
                        if (medicinal != null)
                        {
                            lastBuyMedicinals.Remove(medicinal);
                        }
                    }
                    if (logDebugInfo) ConsoleBLL.WriteLineInfo(this + string.Format(" 获得物品{0}", item.Item.Name));
                }
                else
                {
                    if (logDebugInfo) ConsoleBLL.WriteLineError(this + " 获得未知物品：" + item.Type);
                }
            //});
            return true;
        }

        public bool ProcessItemDroped(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var item = new ItemDropedMsg(x.Data);

                if (item.OwnerID == this.ID)
                {
                    if (logDebugInfo) ConsoleBLL.WriteLineInfo(this + " 掉落物品：" + item.DropedItem.Name + "(" + item.DropedItem.ID.ToString("X") + ")");
                    //   if (!NeedPickupGold && item.DropedItem.Name == "金币")
                    if (item.DropedItem.Name == "金币")
                    {
                        return true;
                    }
                    else if (Config.OnlyPickupSpecify && this.needGetTiems.Count(w => item.DropedItem.Name.Contains(w)) > 0)
                    {
                        GetItem(item);
                    }
                    else if (dontPickupTiems.Count(w => item.DropedItem.Name.Contains(w)) == 0)
                    {
                        GetItem(item);
                    }
                }
            //});
            return true;
        }

        public bool ProcessRide(Message x)
        {
            //var item = new RideMsg(x.Data);
            //if (item.PlayerID == this.ID)
            //{
            //    if (logDebugInfo)
            //    {
            //        if (item.IsRide)
            //        {
            //            ConsoleBLL.WriteLine(this + " 上马");
            //        }
            //        else
            //        {
            //            ConsoleBLL.WriteLine(this + " 下马");
            //        }
            //    }
            //    this.IsRide = item.IsRide;
            //}
            return true;
        }

        //拾到物品
        public bool ProcessItemPickuped(Message x)
        {
            GameHelper.Run(x, r =>
            {
                lock (Items)
                {
                    var item = new ItemPickupedMsg(x.Data);
                    byte Position = 11;

                    if (item.GetedItem.Name == "熊猫" || item.GetedItem.Name == "恶魔")
                    {
                        ZhuangBei(item.InstanceID, this.Version, Position);
                        return;
                    }

                    int[] things = new int[] { 42415, 63150, 34479, 46511, 50351, 44450, 47004, 36777, 65448, 44713, 48809, 52649, 46748 };


                    for (int i = 0; i < 13; i++)
                    {
                        if (item.thingid == things[i])
                        {
                            if (item.thingid == 44450)
                            {
                                if (item.thingids < 240)
                                    Position = 1;       //武器
                                else
                                    Position = 2;       //箭筒
                            }
                            else if (item.thingid == 46748)//双属弓
                                Position = 2;
                            else if (item.thingid == 47004)//箭筒
                                Position = 2;
                            else if (item.thingid == 63150 || item.thingid == 65448)//铠
                                Position = 3;
                            else if (item.thingid == 34479 || item.thingid == 36777) //头盔
                                Position = 4;
                            else if (item.thingid == 42415 || item.thingid == 44713)    //手
                                Position = 6;
                            else if (item.thingid == 46511 || item.thingid == 48809)    //腿
                                Position = 7;
                            else if (item.thingid == 50351 || item.thingid == 52649)    //靴
                                Position = 8;

                            ZhuangBei(item.InstanceID, this.Version, Position);

                            return;
                        }
                    }
                    if (NeedPickupGold == true)
                    {
                        things = new int[] { 42024, 60724, 64820, 39989, 44085, 47925 };
                        for (int i = 0; i < 6; i++)
                        {
                            if (item.thingid == things[i])
                            {
                                if (item.thingid == 42024)
                                {
                                    if (item.thingids < 240)
                                        Position = 1;
                                    else
                                        Position = 2;
                                }
                                else if (item.thingid == 60724)
                                    Position = 3;
                                else if (item.thingid == 64820)
                                    Position = 4;
                                else if (item.thingid == 39989)
                                    Position = 6;
                                else if (item.thingid == 44085)
                                    Position = 7;
                                else if (item.thingid == 47925)
                                    Position = 8;

                                ZhuangBei(item.InstanceID, this.Version, Position);

                                return;
                            }
                        }
                    }

                    if (item.GetedItem.Name == "卓越装备" && Config.AutoTL)
                    {
                        TiLian(item.GetedItem);
                    }

                    else
                    {
                        if (item.GetedItem.Name == "金币") { return; }
                        Items.Add(item.GetedItem);
                    }
                    lock (lastBuyMedicinals)
                    {
                        var medicinal = lastBuyMedicinals.FirstOrDefault(f => f.Name == item.GetedItem.Name);
                        if (medicinal != null)
                        {
                            lastBuyMedicinals.Remove(medicinal);
                        }
                    }
                }
            });
            return true;
        }

        //签到次数
        public bool ProcessSignCount(Message x)
        {
            //GameHelper.Run(x, r =>
            //{
                var item = new SignCountMsg(x.Data);
                ConsoleBLL.WriteLine(this + " 已签到次数：" + item.Count);
            //});
            return true;
        }

        //签到次数
        public bool SellEquipment(Message x)
        {

            var item = new SellEquipmentMsg(x.Data);

            Sell1(item.InstanceID);

            return true;
        }

        public bool ProcessCleanBackpack(Message x)
        {
            var item = new CleanBackpackMsg(x.Data, this);
            for (int i = 0; i < item.ThingNum; i++)
            {
                if (item.GetedItem[i].Name.Contains("宝石"))
                {
                    Items.Add(item.GetedItem[i]);
                    if (item.GetedItem[i].Name.Contains("灵魂") || item.GetedItem[i].Name.Contains("生命"))
                    {
                        Trade = true;
                    }
                }
                else if (item.GetedItem[i].Name == "第一天礼包" || item.GetedItem[i].Name == "寻宝券")
                {
                    贵宾物品已获得.Set();
                    UsePackage(item.GetedItem[i]);
                }
                else if (item.GetedItem[i].Name == "百万金币" || item.GetedItem[i].Name.Contains("2倍经验") || item.GetedItem[i].Name == "千万金币")
                {
                    UseItem(item.GetedItem[i]);
                    Thread.Sleep(500);
                    UseItem(item.GetedItem[i]);
                    Thread.Sleep(500);
                    UseItem(item.GetedItem[i]);
                    Thread.Sleep(500);
                }
                else if (item.GetedItem[i].Name.Contains("等级礼包") || item.GetedItem[i].Name == "会员" || item.GetedItem[i].Name == "攻速卷")
                {
                    UseItem(item.GetedItem[i]);
                }
                else if (item.GetedItem[i].Name == "未知物品" || item.GetedItem[i].Name.Contains("药水"))
                {
                    Sell(item.GetedItem[i]);
                    Items.Remove(item.GetedItem[i]);
                }
                //else
                //    Items.Add(item.GetedItem[i]);
            }

            for (int i = 0; i < item.ThingNum; i++)
            {
                if (item.GetedItem[i].Name.Contains("登陆1"))
                {

                    TradeOver = !TradeOver;
                }
                else if (item.GetedItem[i].Name == "寻宝券")
                {
                    TradeOver = !TradeOver;
                }
            }

            cleanBackpackEvent.Set();
            return true;
        }

        //升级
        public bool ProcessLevelUp(Message x)
        {

            GameHelper.Run(x, r =>
            {
                var item = new LevelUpMsg(x.Data);
                if (item.PlayerID == this.ID)
                {
                    lastLevel++;
                    this.Level = item.Level;

                    //if (this.Level > 119)
                    //{
                    //    Collect();
                    //    //End();
                    //    //Status = PlayerStatusEnum.任务完成;
                    //    //ConsoleBLL.WriteLineInfo(this + "已经到" + this.Level + "级，任务完成。");
                    //    return;
                    //}


                    if (Level < 80) { NeedPickupGold = true; }
                    else
                    {
                        NeedPickupGold = false;

                    }
                    if (Level > 25 && Level <= 101)
                    {
                        engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x97, 0x0D });//整理背包
                        if (Level == 26)
                        {
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDC, 0xA0, 0x9C, 0x01 });//领取恶魔
                            Thread.Sleep(200);
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x97, 0x0D });//整理背包
                        }
                        else if (Level == 40)
                        {
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDC, 0xC0, 0xB8, 0x02 });//领取坐骑
                            Thread.Sleep(200);

                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x19, 0x00, 0x01, 0xD5, 0x99, 0x00, 0x13, 0x00, 0x00, 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 });//激活图标
                            Thread.Sleep(200);
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0xEC, 0xFF });//领取坐骑
                            for (int i = 0; i < 5; i++)
                            {
                                Thread.Sleep(200);
                                engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0xEC, 0xFC, 0x00, 0x00, 0x00 });//坐骑驯养
                            }
                            Thread.Sleep(200);



                        }
                        else if (Level == 48)
                        {
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x08, 0x0F, 0xCB, 0x01 });//发送祈愿
                        }
                        else if (Level == 50)
                        {
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x09, 0x28, 0x8C, 0x0E });//领取50级等级奖励
                        }
                        else if (Level == 54)
                        {
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDC, 0xE0, 0xD4, 0x03 });//激活血色城堡
                            Thread.Sleep(200);
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0xf4, 0xd5, 0x00 });//激活图标

                        }
                        else if (Level == 59)
                        {
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDC, 0x80, 0xf1, 0x04 });//激活恶魔广场
                            Thread.Sleep(200);
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0xf4, 0xd5, 0x00 });//激活图标
                        }
                        else if (Level == 94)
                        {
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDC, 0xA0, 0x8D, 0x06 });//激活精英挑战
                            Thread.Sleep(500);
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0xf4, 0xd5, 0x00 });//激活图标
                            Thread.Sleep(500);
                            //engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x09, 0x28, 0x8E, 0x02 });//激活怒意加深
                            // engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x09, 0x28, 0x89 });//领取精魄
                            for (int i = 0; i < 4; i++)
                            {
                                Thread.Sleep(200);
                                engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x09, 0x28, 0x8E, 0x02 });//激活怒意加深
                            }


                        }
                        else if (this.Level == 100)
                        {

                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDC, 0xC0, 0xA9, 0x07 });//领取熊猫
                            Thread.Sleep(500);
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x09, 0x28, 0x8C, 0x0C });//领取100级等级奖励
                            Thread.Sleep(500);
                            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x08, 0x0F, 0xCB, 0x03 });//发送祈愿精魄
                            for (int i = 0; i < 20; i++)
                            {
                                Thread.Sleep(300);
                                engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0xEC, 0xFC, 0x00, 0x00, 0x00 });//坐骑驯养
                            }
                            for (int i = 0; i < 40; i++)
                            {
                                Thread.Sleep(300);
                                engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x09, 0x28, 0x8E, 0x02 });//激活怒意加深
                            }
                        }

                    }

                }
                if (item.Level > 29)
                    this.engine.SendData(DataPackager.GetAddPointData());// 加点

                var fightMapLocation = Player.BotFightLocations.OrderByDescending(w => w.Level).FirstOrDefault(w => this.Level >= w.Level);//查找当前等级应该去的练级地址
                var point = fightMapLocation.LocationPoints.LastOrDefault();

                if (fightMapLocation != null && FightMapLocation != null && fightMapLocation.MapName != FightMapLocation.MapName && point != FightLocation)
                {
                    //ConsoleBLL.WriteLine(this + " 更换练级地址为：" + fightMapLocation.MapName + "，重新开始挂机");
                    //FightMapLocation = fightMapLocation;
                    this.AutoFight = false;
                    Status = PlayerStatusEnum.重新开始挂机;
                    GameHelper.RunThread(ReFight);
                }
            });

            return true;
        }
        #endregion

        #region 交易消息处理

        /// <summary>
        /// 收到仓库号锁定
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        private bool ProcessLockTrade(Message x)
        {
            var item = new LockTradeMsg(x.Data);
            if (item.InvitePlayerID != this.ID && item.InviteTrue == 2)
            {
                ConsoleBLL.WriteLine(string.Format("仓库号已锁定并确认交易"));
                tradeEvent.Set();
            }
            return true;
        }

        /// <summary>
        /// 收到仓库号同意交易
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        private bool ProcessAgreeTrade(Message x)
        {
            var item = new AgreeTradeMsg(x.Data);
            ConsoleBLL.WriteLine("仓库号已同意交易");
            tradeEvent.Set();

            return true;
        }
        #endregion

        #region 贵宾活动页面
        public bool ProcessGiftUrl(Message x)
        {
            GameHelper.Run(x, r =>
            {
                try
                {
                    ConsoleBLL.WriteInfo("收到贵宾活动页面地址");
                    var url = UTF8Encoding.UTF8.GetString(x.Data, 2, x.Data.Length - 2);
                    ConsoleBLL.WriteInfo(url);
                    var request = net.SendRequest(url, "GET", Cookie);
                    var html = net.GetResponseHtmlGzip(request);

                    request = net.SendRequest(string.Format(GET_LOGIN_GIFT_URL, DateTime.Now.ToFileTime()), "GET", Cookie);
                    html = net.GetResponseHtml(request);
                    html = html.Replace("a(", "").Replace(");", "");
                    JObject result = (JObject)JsonConvert.DeserializeObject(html);
                    ConsoleBLL.WriteLineInfo(result["msg"].ToString());
                    if (result["msg"].ToString().Contains("频繁") || result["msg"].ToString().Contains("失败"))
                    {
                        NeedLevel = false;
                    }
                    else
                        NeedLevel = true;
                }
                catch (Exception ex)
                {
                    ConsoleBLL.WriteError(ex.Message);
                }

                giftGot = true;
            });
            return true;
        }
        #endregion

        #region 邮箱数据处理
        public bool ProcessMailData(Message x)
        {
            GameHelper.Run(x, r =>
            {
                var item = new ProcessMailDataMsg(x.Data);

                if (item.ThingID != 0)
                    OpenMail(item.ThingID);
                ConsoleBLL.WriteLineInfo("收到邮箱数据");
                var data = UTF8Encoding.UTF8.GetString(x.Data);
                ConsoleBLL.WriteInfo(data);
                mailboxOpend.Set();
            });

            return true;
        }
        #endregion

        public bool ProcessTreasureData(Message x)
        {

            var item = new ProcessTreasureData(x.Data, this);

            for (int i = 0; i < item.ThingNum; i++)
            {
                if (item.GetedItem[i].Name.Contains("宝石"))
                {

                    Trade = true;   //需要交易
                }

            }
            寻宝结果.Set();
            return true;
        }

        private void GetGiftItem()
        {
            GetGift();//领取贵宾礼品
            while (!giftGot)
            {
                Thread.Sleep(1000);
            }
            mailboxOpend.Reset();
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0xE4, 0xF7 }); //打开邮件
            if (!mailboxOpend.WaitOne(1000 * 30))
            {
                ConsoleBLL.WriteLineError(string.Format("打开邮件超时！", this));
                Status = PlayerStatusEnum.等待;
                Quit();
                Thread.Sleep(500);
                return;
            }
            Thread.Sleep(3000);
            cleanBackpackEvent.Reset();
            贵宾物品已获得.Set();
            tradeCompleted = true;
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x97, 0x0D }); //整理背包
            if (!cleanBackpackEvent.WaitOne(1000 * 10))
            {
                ConsoleBLL.WriteLineError(string.Format("等待整理背包超时！", this));
                Status = PlayerStatusEnum.等待;
                Quit();
                Thread.Sleep(500);
                return;
            }


            if (!贵宾物品已获得.WaitOne(10 * 1000))
            {
                ConsoleBLL.WriteLineError(string.Format("获取贵宾物品超时！", this));
                Status = PlayerStatusEnum.等待;
                Quit();
                Thread.Sleep(500);
                return;
            }

            return;
            if (Items.Count == 0 && Trade == true)
            {
                ConsoleBLL.WriteLineError(string.Format("已经进行过交易！", this));
                Quit();
                Thread.Sleep(500);
                Status = PlayerStatusEnum.任务完成;
                return;
            }
            else if (Items.Count == 0 && Trade == false)
            {
                ConsoleBLL.WriteLineError(string.Format("没有获取到交易物品！", this));
                Quit();
                Thread.Sleep(500);
                Status = PlayerStatusEnum.等待;
                return;
            }

            if (Items.Count > 0)
            {
                ConsoleBLL.WriteLine("有物品需要交易：");
                Items.ForEach(x =>
                {
                    ConsoleBLL.WriteLineInfo(x.Name);
                });
            }

            Transmit(Master.CurrentMap);    //移动到仓库号所在地图
            Thread.Sleep(1000);
            Change(1); //换线

            tradeEvent.Reset();
            InviteTrade(Master.ID);
            //等待对方同意(60秒超时)
            if (!tradeEvent.WaitOne(1000 * 10))
            {
                ConsoleBLL.WriteLineError(string.Format("等待{0}同意交易超时，交易取消！", this));
                Status = PlayerStatusEnum.等待;
                return;
            }
            lock (Items)
            {
                for (int i = 0; i < Items.Count && i < 6; i++)
                {
                    PutItem(Items[i], (short)(i + 1));
                    Thread.Sleep(200);
                }

                Thread.Sleep(500);
                LockTrade();//发送锁定
            }
            // Thread.Sleep(500);
            tradeEvent.Reset();
            if (!tradeEvent.WaitOne(1000 * 10))
            {
                ConsoleBLL.WriteLineError(string.Format("等待{0}锁定交易超时，交易取消！", this)); //return;
                Status = PlayerStatusEnum.等待;
                return;
            }

            AffirmTrade();//发送确认

            Quit();
            Thread.Sleep(500);
            Status = PlayerStatusEnum.任务完成;
        }

        protected bool GetGift()
        {
            giftGot = false;
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x08, 0x03, 0x96 });
            int j = 0;
            while (!giftGot)
            {
                Thread.Sleep(1500);
                j++;
                if (j == 10)
                {
                    ConsoleBLL.WriteLineError(string.Format("领取礼包超时！", this));

                    return false;
                }
            }
            return giftGot;
        }
    }
}
